using System.Text.RegularExpressions;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace OrbitOne.CRMLyncInfoDashboard.CRM.Plugins
{
    public static class Extensions
    {
        public static string CleanupNonAlphanumeric(this object source, Regex regex)
        {
            return source == null
                       ? ""
                       : regex.Replace(source.ToString(), string.Empty);
        }

        public static Entity GetEntity(this IOrganizationService service, IPluginExecutionContext context)
        {
            return service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true));
        } 


        public static Entity EnsureEntity(this IOrganizationService service, Entity entity, IPluginExecutionContext context)
        {
            var fullEntity = service.GetEntity(context);
            fullEntity.FillWithAttributesFrom(entity);
            return fullEntity;
        }

        public static void FillWithAttributesFrom(this Entity fullEntity, Entity entity)
        {
            foreach (var attribute in entity.Attributes)
            {
                fullEntity[attribute.Key] = attribute.Value;
            }
        }
    }
}